package com.online.onlineshop.controllers;


import com.alibaba.fastjson.JSONObject;
import com.online.onlineshop.entity.User;
import com.online.onlineshop.services.ForUserService;
import com.online.onlineshop.utils.ControllerUtil;
import com.online.onlineshop.utils.ResultForFrontEnd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserController extends RootController {

    @Autowired
    private ForUserService userService;


    @RequestMapping("register")
    @ResponseBody
    public ResultForFrontEnd<Void> register(User user) {
        //进行响应结果对象的创建

        userService.register(user);
        return new ResultForFrontEnd<>(ok);
    }

    //登录请求处理

    /**
     * @username 用户名
     * @password 密码
     */
    @RequestMapping("login")
    public ResultForFrontEnd<User> login(HttpServletResponse response, String username, String password, HttpSession session) {
        //进行响应结果对象的创建
        User loginUser = userService.login(username, password);
        session.setAttribute("uid", loginUser.getUid());
        session.setAttribute("username", loginUser.getUsername());
        session.setAttribute("userType", loginUser.getUserType());

        return new ResultForFrontEnd<User>(ok, loginUser);
    }

    @RequestMapping("showName")
    public void showName(HttpServletRequest request, HttpServletResponse response) {
        Object user = request.getSession().getAttribute("username");
        Object userType = request.getSession().getAttribute("userType");
        JSONObject jsonObject = new JSONObject();
        if (user == null) {
            jsonObject.put("username", "");
        }
        jsonObject.put("username", user);
        jsonObject.put("userType", userType);
        ControllerUtil.writeJson(response, jsonObject.toJSONString());
    }

    @RequestMapping("updatePassword")
    public ResultForFrontEnd<Void> updatePassword(String oldPassword, String newPassword, HttpSession session) {

        int uid = getUidFromSession(session);
        userService.updatePassword(uid, oldPassword, newPassword);
        return new ResultForFrontEnd<>(ok);

    }

    @RequestMapping("updateInfo")
    public ResultForFrontEnd<Void> updateInfo(User user, HttpSession session) {
        int uid = getUidFromSession(session);
        String userName = getUserNameFromSession(session);
        userService.updateInfo(uid, userName, user);
        return new ResultForFrontEnd<>(ok);

    }

    @RequestMapping("getUserByUid")
    public ResultForFrontEnd<User> getUserByUid(HttpSession session) {

        int uid = getUidFromSession(session);
        User userByUid = userService.getByUid(uid);
        return new ResultForFrontEnd<>(ok, userByUid);
    }

    //文件大小限制
    public static final int MAX_UPLOAD = 10 * 1024 * 1024;

    public static final List<String> fileType = new ArrayList<String>();

    static {
        fileType.add("image/jpeg");
        fileType.add("image/png");

    }

    @RequestMapping("changePortrait")
    public ResultForFrontEnd<String> changePortrait
            (HttpSession session, MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        if (file.getSize() > MAX_UPLOAD) {
            throw new RuntimeException("文件过大");
        }

        String contentType = file.getContentType();
        if (!fileType.contains(contentType)) {
            throw new RuntimeException("文件类型不支持");

        }
        String master = session.getServletContext().getRealPath("upload");

        File dir = new File(master);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(i);
        String fileName = UUID.randomUUID().toString().toUpperCase() + suffix;
        File dest = new File(dir, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("写入异常");
        }
        int uid = getUidFromSession(session);
        String userName = getUserNameFromSession(session);
        String path = "/upload/" + fileName;

        userService.changePortrait(uid, path, userName);

        return new ResultForFrontEnd<>(ok, path);

    }


}
